package com.bkfm.framework.core.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.yak.core.web.Result;
import org.yak.core.web.Result.Status;

/**
 *
 * @平台：Rest入口统一异常处理
 * @文件名称：RestExceptionHandler.java
 * @文件描述：Rest请求入口异常处理
 * @author XQ
 * @日期：2018年5月15日上午9:34:39
 *
 */
@RestControllerAdvice
public class RestExceptionHandler {

	private static final Logger logger = Logger.getLogger(RestExceptionHandler.class);

    @ResponseBody
    @org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
    public Result handleUnexpectedServerError(HttpServletRequest request, HttpServletResponse res, Object handler,Exception ex) {
    	logger.error("请求异常",ex);
        // 处理异常
        Result response = new Result();
        response.setStatus(Status.ERROR);
        if (ex instanceof HttpRequestMethodNotSupportedException) {
        	response.setMessage("405, 请求方式错误！");
        }else if (ex instanceof MissingServletRequestParameterException) {
            response.setMessage("400, 请求方式错误！");
        }else if(ex instanceof NoHandlerFoundException){
        	response.setMessage("404-请求的地址或者页面不存在！");
        }else{
        	response.setMessage("500-系统请求异常");
        }

        // 返回数据
        return response;
    }
}
